/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkClass } from 'arkanalyzer/lib/core/model/ArkClass';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { ViewTreeNode, Stmt, ArkMethod, ArkInstanceFieldRef, MethodSignature, ArkInvokeStmt, ArkAssignStmt, Local } from 'arkanalyzer';
import { Rule, Defects, ClassMatcher, MatcherTypes, MatcherCallback, MethodMatcher } from '../../Index';
import { ViewTreeTool } from '../../utils/checker/ViewTreeTool';
import { IssueReport } from '../../model/Defects';
import { Constant, NumberConstant } from 'arkanalyzer/lib/core/base/Constant';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'IneffectiveLayoutWeightCheck');
const gMetaData: BaseMetaData = {
    severity: 3,
    ruleDocPath: 'docs/ineffective-layoutweight-check.md',
    description: 'When only one child component in a Row or Column container uses layoutWeight, you should set the width or height of this component to 0.'
};
const viewTreeTool = new ViewTreeTool();
interface AttributeInfo {
    weightOrHeight: boolean;
    layoutWeight: boolean;
    stmt: Stmt | null;
}
export class IneffectiveLayoutWeightCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private clsMatcher: ClassMatcher = {
        matcherType: MatcherTypes.CLASS,
        hasViewTree: true
    };
    private mtdMatcher: MethodMatcher = {
        matcherType: MatcherTypes.METHOD,
        hasViewTree: true
    };

    public registerMatchers(): MatcherCallback[] {
        const matchClazzCb: MatcherCallback = {
            matcher: this.clsMatcher,
            callback: this.check
        };
        const matchMethodCb: MatcherCallback = {
            matcher: this.mtdMatcher,
            callback: this.check
        };
        return [matchClazzCb, matchMethodCb];
    }

    public check = (target: ArkClass | ArkMethod): void => {
        let viewTreeRoot = target.getViewTree()?.getRoot();
        if (!viewTreeRoot) {
            return;
        }
        this.traverseViewTree(viewTreeRoot);
    };

    private traverseViewTree(viewTreeRoot: ViewTreeNode): void {
        if (viewTreeRoot === undefined || viewTreeTool.hasTraverse(viewTreeRoot)) {
            return;
        }
        let name = viewTreeRoot.name;
        if ((name === 'Row' || name === 'Column')) {
            this.hasLayoutWeight(viewTreeRoot.children);
        }
        for (let child of viewTreeRoot.children) {
            this.traverseViewTree(child);
        }
    }

    private hasLayoutWeight(children: ViewTreeNode[]): void {
        let attributeInfos: AttributeInfo[] = [];
        for (let child of children) {
            let attributeInfo: AttributeInfo = {
                weightOrHeight: false,
                layoutWeight: false,
                stmt: null
            };
            let attributes = child.attributes;
            let layoutWeight = attributes.get('layoutWeight');
            if (!layoutWeight) {
                continue;
            } else {
                attributeInfo.layoutWeight = true;
                this.getStmtByValues(layoutWeight[0], attributeInfo);
            }
            let width = attributes.get('width');
            this.getFlagByValue(width, attributeInfo);
            let height = attributes.get('height');
            this.getFlagByValue(height, attributeInfo);
            if (attributeInfo.layoutWeight && attributeInfo.weightOrHeight) {
                continue;
            }
            attributeInfos.push(attributeInfo);
        }
        if (attributeInfos.length !== 1) {
            return;
        }
        this.reportIssue(attributeInfos[0].stmt, 'layoutWeight');
    }

    private getStmtByValues(stmt: Stmt, attributeInfo: AttributeInfo): void {
        if (stmt instanceof ArkInvokeStmt) {
            attributeInfo.stmt = stmt;
        }
        if (stmt instanceof ArkAssignStmt) {
            let leftOp = stmt.getLeftOp();
            if (!(leftOp instanceof Local)) {
                return;
            }
            attributeInfo.stmt = leftOp.getDeclaringStmt();
        }
    }

    private getFlagByValue(stmts: [Stmt, (Constant | ArkInstanceFieldRef | MethodSignature)[]] | undefined, attributeInfo: AttributeInfo): void {
        if (!stmts) {
            return;
        }
        let values = stmts[1];
        if (!(values instanceof Array)) {
            return;
        }
        let value = values[0];
        if (!(value instanceof NumberConstant)) {
            return;
        }
        let num = parseInt(value.getValue());
        if (num !== 0) {
            return;
        }
        attributeInfo.weightOrHeight = true;
    }

    private reportIssue(stmt: Stmt | null, key: string): void {
        if (!stmt) {
            return;
        }
        const severity = this.rule.alert ?? this.metaData.severity;
        const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile();
        const originPosition = stmt.getOperandOriginalPosition(stmt.getDefAndUses().length - 1);
        if (!(arkFile && originPosition)) {
            return;
        }
        const lineNum = originPosition.getFirstLine();
        const endColunm = originPosition?.getFirstCol() - 1;
        const startColumn = endColunm - key.length;
        const filePath = arkFile.getFilePath();
        let defects = new Defects(lineNum, startColumn, endColunm, this.metaData.description, severity, this.rule.ruleId,
            filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defects, undefined));
    }
}